//
//  ATMotionManager.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/11.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//

#import "ATMotionManager.h"
#import <CoreMotion/CoreMotion.h>

@interface ATMotionManager ()

/** 注意，当前应用只能有一个CMMotionManager实例，多个实例会影响接收速率 */
@property (strong, nonatomic) CMMotionManager *motionManager;

/** <#name#> */
@property (nonatomic, assign) NSInteger stopCount;

/** <#name#> */
@property (nonatomic, assign) BOOL isRunning;

/** 加速仪结果回调 */
@property (nonatomic, copy) ATCompletionBlock completionBlock;

@end

@implementation ATMotionManager

+ (instancetype)manager
{
    return [[self alloc] init];
}

- (instancetype)init
{
    if (self = [super init]) {
        self.motionManager = [[CMMotionManager alloc] init];
        self.motionManager.accelerometerUpdateInterval = 0.1;//加速仪更新频率，以秒为单位
    }
    return self;
}

- (void)startGyroUpdates
{
    NSOperationQueue* queue = [[NSOperationQueue alloc]init];
    
    __weak typeof(self) weakSelf = self;
    /**
     *  陀螺仪是否可用
     */
    if (self.motionManager.gyroAvailable) {
        
        [self.motionManager startGyroUpdatesToQueue:queue withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) {
            
            float y = gyroData.rotationRate.y;
            
            float z = gyroData.rotationRate.z;
            
            NSLog(@"y == %f, z === %f", y, z);
            
            if (fabs(y)>2||fabs(z)>2) {
                
                weakSelf.stopCount = 0;
                
                if(!weakSelf.isRunning) weakSelf.isRunning = YES;
                
            }else{
                
                weakSelf.stopCount++;
                
                if (weakSelf.stopCount > 8) {
                    
                    if(weakSelf.isRunning) weakSelf.isRunning = NO;
                }
            }
        }];
    }else{
        NSLog(@"陀螺仪不可用");
    }
}

- (void)start:(ATCompletionBlock)completinBlock
{
//    _completionBlock = completinBlock;
    
    [self.motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        
//        NSLog(@"2---y===%f, z===%f", accelerometerData.acceleration.y, accelerometerData.acceleration.z);
        
        if (error) {
            NSLog(@"加速仪报错 error:%@", error);
        } else {
            //综合3个方向的加速度
            double accelerameter =sqrt(pow(accelerometerData.acceleration.x, 2) + pow(accelerometerData.acceleration.y, 2) + pow(accelerometerData.acceleration.z, 2));
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completinBlock) {
                    completinBlock(accelerameter);
                }
                
            });
        }
    }];
}

- (void)stop
{
    // 结束监听
    [self.motionManager stopAccelerometerUpdates];
}

@end
